package com.lbj.yuanxi.yx001

import android.app.*
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Build
import android.os.IBinder
import androidx.core.app.NotificationCompat
import com.lbj.yuanxi.R

class FloatingWindowService : Service() {

    private var channelId = "FloatingWindowService"
    override fun onBind(intent: Intent?): IBinder? {
        return null
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        return super.onStartCommand(intent, flags, startId)
    }

    override fun onCreate() {
        super.onCreate()
        addForegroundNotification()
        FloatingWindowManager.getInstance(this).showCircleView()
    }

    private fun addForegroundNotification() {
        createNotificationChannel()
        val contentTitle = "浮窗小球"
        val contentText = "浮窗小球正在运行中"
        val mBuilder: NotificationCompat.Builder = NotificationCompat.Builder(
            applicationContext,
            channelId
        )
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentTitle(contentTitle)
            .setContentText(contentText)
            .setWhen(System.currentTimeMillis())
            .setPriority(NotificationCompat.PRIORITY_DEFAULT)
        val msgIntent: Intent = getStartAppIntent(applicationContext)
        val mainPendingIntent = PendingIntent.getActivity(
            applicationContext, 0,
            msgIntent, PendingIntent.FLAG_UPDATE_CURRENT
        )
        val notification: Notification = mBuilder.setContentIntent(mainPendingIntent)
            .setAutoCancel(false).build()
        startForeground(
            1,
            notification
        )
    }

    private fun getStartAppIntent(context: Context): Intent {
        val intent = context.packageManager
            .getLaunchIntentForPackage(context.packageName)
        intent?.addFlags(
            Intent.FLAG_ACTIVITY_NEW_TASK
                    or Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED
        )
        return intent!!
    }

    private fun createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val name: CharSequence = "Name"
            val description = "Description"
            val importance = NotificationManager.IMPORTANCE_DEFAULT
            val channel = NotificationChannel(
                channelId,
                name,
                importance
            )
            channel.enableLights(true)
            channel.lightColor = Color.RED
            channel.lockscreenVisibility = Notification.VISIBILITY_PUBLIC
            channel.setShowBadge(true)
            channel.description = description
            val notificationManager = getSystemService(
                NotificationManager::class.java
            )
            notificationManager?.createNotificationChannel(channel)
        }
    }
}